from flask import Blueprint, render_template, jsonify, send_from_directory, request
from flask_login import login_required
from app.utils.decorators import admin_required
import os
import json

game_bp = Blueprint('game', __name__)

# 配置路径
def get_static_folder():
    """获取static文件夹路径"""
    return os.path.join(os.path.dirname(os.path.dirname(__file__)), 'static')

def get_songs_db_path():
    """获取songs.json路径"""
    return os.path.join(get_static_folder(), 'game', 'songs.json')

def load_songs_db():
    """加载歌曲数据库"""
    songs_db_path = get_songs_db_path()
    if not os.path.exists(songs_db_path):
        return []
    try:
        with open(songs_db_path, 'r', encoding='utf-8') as f:
            return json.load(f)
    except Exception as e:
        print(f"加载歌曲数据库失败: {e}")
        return []

def save_songs_db(songs):
    """保存歌曲数据库"""
    songs_db_path = get_songs_db_path()
    try:
        with open(songs_db_path, 'w', encoding='utf-8') as f:
            json.dump(songs, f, ensure_ascii=False, indent=2)
        return True
    except Exception as e:
        print(f"保存歌曲数据库失败: {e}")
        return False

@game_bp.route('/')
def index():
    """游戏主页面"""
    return render_template('game/index.html')

@game_bp.route('/api/songs')
def get_songs():
    """获取可用歌曲列表"""
    songs = load_songs_db()
    return jsonify({
        'success': True,
        'songs': songs
    })

@game_bp.route('/api/songs/<int:song_id>/chart')
def get_chart(song_id):
    """获取指定歌曲的谱面数据"""
    songs = load_songs_db()

    # 查找歌曲
    song = next((s for s in songs if s['id'] == song_id), None)
    if not song:
        return jsonify({'success': False, 'error': '歌曲不存在'}), 404

    static_folder = get_static_folder()
    charts_dir = os.path.join(static_folder, 'game', 'charts')
    chart_path = os.path.join(charts_dir, song['chart_file'])

    if not os.path.exists(chart_path):
        return jsonify({'success': False, 'error': '谱面文件不存在'}), 404

    try:
        with open(chart_path, 'r', encoding='utf-8') as f:
            chart_data = json.load(f)
        return jsonify({
            'success': True,
            'chart': chart_data
        })
    except Exception as e:
        return jsonify({'success': False, 'error': f'读取谱面失败: {str(e)}'}), 500

@game_bp.route('/api/songs/<int:song_id>/audio')
def get_audio(song_id):
    """流式传输指定歌曲的音频文件"""
    songs = load_songs_db()

    # 查找歌曲
    song = next((s for s in songs if s['id'] == song_id), None)
    if not song:
        return jsonify({'success': False, 'error': '歌曲不存在'}), 404

    static_folder = get_static_folder()
    songs_dir = os.path.join(static_folder, 'game', 'songs')
    audio_path = os.path.join(songs_dir, song['audio_file'])

    if not os.path.exists(audio_path):
        return jsonify({'success': False, 'error': '音频文件不存在'}), 404

    return send_from_directory(songs_dir, song['audio_file'])

# ==================== 管理功能 ====================

@game_bp.route('/manage')
@login_required
@admin_required
def manage():
    """歌曲管理页面（需要管理员权限）"""
    songs = load_songs_db()
    return render_template('game/manage.html', songs=songs)

@game_bp.route('/api/songs/add', methods=['POST'])
@login_required
@admin_required
def add_song():
    """添加新歌曲（需要管理员权限）"""
    try:
        data = request.get_json()

        # 验证必填字段
        required_fields = ['title', 'artist', 'chart_file', 'audio_file']
        for field in required_fields:
            if not data.get(field):
                return jsonify({'success': False, 'error': f'{field} 不能为空'}), 400

        # 加载现有歌曲
        songs = load_songs_db()

        # 生成新ID
        new_id = max([s['id'] for s in songs], default=0) + 1

        # 创建新歌曲
        new_song = {
            'id': new_id,
            'title': data['title'],
            'artist': data['artist'],
            'difficulty': data.get('difficulty', 'Normal'),
            'level': int(data.get('level', 5)),
            'chart_file': data['chart_file'],
            'audio_file': data['audio_file']
        }

        songs.append(new_song)

        if save_songs_db(songs):
            return jsonify({'success': True, 'song': new_song})
        else:
            return jsonify({'success': False, 'error': '保存失败'}), 500

    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500

@game_bp.route('/api/songs/<int:song_id>/delete', methods=['DELETE'])
@login_required
@admin_required
def delete_song(song_id):
    """删除指定歌曲（需要管理员权限）"""
    try:
        songs = load_songs_db()

        # 查找歌曲
        song = next((s for s in songs if s['id'] == song_id), None)
        if not song:
            return jsonify({'success': False, 'error': '歌曲不存在'}), 404

        # 删除歌曲
        songs = [s for s in songs if s['id'] != song_id]

        if save_songs_db(songs):
            return jsonify({'success': True, 'message': '删除成功'})
        else:
            return jsonify({'success': False, 'error': '保存失败'}), 500

    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 500
